package org.jeecg.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.annotations.OrgPermissionAnnotation;
import org.jeecg.config.util.CurrentOrgInfoUtil;
import org.jeecg.modules.fk.entity.DjOrg;
import org.jeecg.modules.fk.service.IDjOrgService;
import org.jeecg.modules.fk.utils.CheckRoleUtil;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

/**
 * 企业权限拦截器，判断该用户对当前请求的企业是否有查询权限
 * 1.超管或省行领导，对所有企业有权限。
 * 2.分支行领导，对当前分支行下的企业有权限。
 * 3.管户经理，只对当前管户企业有权限
 * @author chensherun on 2023/4/18.
 * @version 1.0
 */
@Component
@Slf4j
public class OrgPermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IDjOrgService djOrgService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //只拦截有配置注解的
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        OrgPermissionAnnotation orgAuthAnnotation = handlerMethod.getMethodAnnotation(OrgPermissionAnnotation.class);
        if (orgAuthAnnotation == null) {
            return true;
        }
        String shxydm = request.getHeader("shxydm");
        if (StringUtils.isBlank(shxydm) || shxydm.equals("null") || shxydm.equals("undefinded")) {
            //throw new JeecgBootException("鉴权失败：企业社会信用代码不能为空");
            Result result = Result.error(CommonConstant.SC_JEECG_NO_AUTHZ, "鉴权失败：企业社会信用代码不能为空");
            writeResponse(response, result);
            return false;
        }
        //获取用户角色
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Set<String> roleNameListString = sysUserService.getUserRolesSet(loginUser.getUsername());
        String orgCode = loginUser.getOrgCode();
        DjOrg djOrg = djOrgService.getByNsrsbhOrShxydm(shxydm);
        //判断是否为部门领导，若是则添加部门前缀作为查询条件
        if (CheckRoleUtil.checkIsDeptAdmin(roleNameListString)) {
            if (StringUtils.isBlank(djOrg.getSaleNetCode()) || !djOrg.getSaleNetCode().startsWith(orgCode)) {
                //throw new JeecgBootException("对不起，你没有该企业的查询权限。");
                Result result = Result.error(CommonConstant.SC_JEECG_NO_AUTHZ, "对不起，你没有该企业的查询权限。");
                writeResponse(response, result);
                return false;
            }
        } else if (!CheckRoleUtil.checkIsSysAdmin(roleNameListString)) {
            //不是部门领导，也不是管理员，则只能查询管户
            if (!loginUser.getId().equals(djOrg.getManageUserId())) {
                //throw new JeecgBootException("对不起，你没有该企业的查询权限。");
                Result result = Result.error(CommonConstant.SC_JEECG_NO_AUTHZ, "对不起，你没有该企业的查询权限。");
                writeResponse(response, result);
                return false;
            }
        }
        CurrentOrgInfoUtil.setCurrentOrgShxydm(shxydm);
        return true;
    }
//
//    private void pushRequest2Body(HttpServletRequest request, HandlerMethod handlerMethod, String shxydmCol, String shxydm) {
//        try{
//            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
//            if(ArrayUtils.isEmpty(methodParameters)) {
//                return;
//            }
//            if(request instanceof RequestWrapper){
//                RequestWrapper requestWrapper = (RequestWrapper)request;
//                String body = requestWrapper.getBody();
//                JSONObject param = JSONObject.parseObject(body).getJSONObject("body");
//                if (param != null) {
//                    param.put(shxydmCol, shxydm);
//                }
//                requestWrapper.setBody(JSON.toJSONString(param));
//            }
//        }catch (Exception e){
//            log.warn("fill userInfo to request body Error ", e);
//        }
//    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        CurrentOrgInfoUtil.remove();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    private void writeResponse(ServletResponse response, Result result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(result));
        out.flush();
        out.close();
    }

    private void writeResponse(ServletResponse response, String responseString)
            throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(responseString);
        out.flush();
        out.close();
    }
}
